package com.cykj.pos.util;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @project: zbh-api
 * @package: vip.zhongbaohui.api.product.saas.core.util
 * @class: AESUtil
 * @description: AES加密工具类
 */
@Component
public class YlgUtil {
    private static Logger logger = LoggerFactory.getLogger(YlgUtil.class);

    public final static String APPID = "edf844fae5f945f7ad7e28b052b18ebf";
    public final static String CODE = "YLGb1d4277a2ac14d4d96bcfe349cbbbec6";
    public final static String PUBLICKEY = "3059301306072a8648ce3d020106082a811ccf5501822d034200042226936225113e6fb6d779e261557fcd607ef3d40149d24cbc7dcf1d33f7ec5d1a2f8a9a095bdef74138cff55601fd40ae33cec6961e121cbafe99983ed8355e";
    public final static String PRIVATEKEY = "308193020100301306072a8648ce3d020106082a811ccf5501822d047930770201010420f0d4962f2ce5dda69dd654000f69103ef352817fc79648d1cce379e580d2bf85a00a06082a811ccf5501822da144034200042226936225113e6fb6d779e261557fcd607ef3d40149d24cbc7dcf1d33f7ec5d1a2f8a9a095bdef74138cff55601fd40ae33cec6961e121cbafe99983ed8355e";
    public final static String PRODAPI = "https://sso.ylg123.cn";
    public final static String TESTAPI = "http://47.93.160.156:8020";


    public static String getContent(Long timestampNow){
        String content = "APPID=" + APPID + "&CODE=" + CODE + "&TIMESTAMP=" + timestampNow;
        return content;
    }

    public static SM2 sm2 (){
        return SmUtil.sm2(PRIVATEKEY, PUBLICKEY);
    }

    public static String YLG_POST(String url,String body){
        Long timestampNow = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        String sign = sm2().signHex(HexUtil.encodeHexStr(getContent(timestampNow)));
        String encryptBody = YlgUtil.sm2().encryptHex(body, KeyType.PublicKey);
        return HttpRequest.post(PRODAPI+url)
                .header("timestamp", timestampNow + "")
                .header("appId", APPID)
                .header("content-type","application/json")
                .header("sign", sign)
                .header("algSm", "SM2")
                .body(encryptBody)
                .timeout(20000)
                .execute().body();
    }


}
